<template>
  <div className="map-wrapper">
    <div id="panel"></div>
    <div style="position: absolute;top: 0;height: 30px;left: 100px;width: 800px;z-index: 999;margin-left: 200px;display: flex">
      <el-input v-model="searchText" placeholder="请输入搜索关键字" id="searchInputId"/>


      <el-input v-model="startName" style="margin-right: 10px" placeholder="起始地点"></el-input>
      <el-input id="end" v-model="endName" style="margin-right: 10px" placeholder="目的地点"></el-input>
      <el-select v-model="rule">
        <el-option
            v-for="item in routeRules"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            placeholder="请选择驾车算路策略"
        />

      </el-select>
      <el-button @click="goView" style="margin-left: 10px">搜索</el-button>
    </div>
    <div style="height: 400px;width: 320px;position: absolute;top:100px;z-index: 9999;border: 1px springgreen solid" v-if="routeArr.length>0">
      路线规划策略:{{policy}}
      <el-row v-for="(item,index) in routeArr" :key="index">
        {{item.instruction}}
      </el-row>
    </div>
    <div id="amap"></div>
    <!-- 天气信息面板 -->
    <div class="weather-panel" v-if="weatherInfo.weather">
      <div class="weather-header">{{ weatherInfo.city }}</div>
      <div class="weather-body">
        <div class="temperature">{{ weatherInfo.temperature }}°C</div>
        <div class="weather-condition">{{ weatherInfo.weather }}</div>
      </div>
      <div class="weather-footer">
        <span>风向: {{ weatherInfo.windDirection }}</span>
        <span>风力: {{ weatherInfo.windPower }} 级</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import {onMounted, onUnmounted, ref} from "vue";
import {useUserStore} from "@/pinia/index.js";

// 安全配置,
window._AMapSecurityConfig = {
  securityJsCode: "bf22f536741b7ddf73ab2a36fe06c9e4",
};

// 变量声明（移除类型注解）
let map = null;
let placeSearch = null;
let AMapObj = null;
let geocoder = null;
let mouseTool = null;
var useUserStore1 = useUserStore();
let circleId = 1;
let startName=ref('')
let endName=ref('')
startName.value = useUserStore1.getOrdStartName;
endName.value = useUserStore1.getOrdEndName;
let rule=ref('')
let policy=ref('')
const routeRules = [
  {
    value: 0,
    label: '速度优先',
  },
  {
    value: 1,
    label: '费用优先',
  },
  {
    value: 2,
    label: '距离优先',
  },
  {
    value: 41,
    label: '躲避拥堵＋少收费',
  },
  {
    value: 32,
    label: '默认',
  },
]
let routeArr = ref([])
let auto = ref('');
let autoOptions = {
  input: 'searchInputId',
};
let searchText = ref('');
let weatherInfo = ref({}); // 天气信息

onMounted(() => {
  initMap();
});

async function initMap() {
  try {
    const AMap = await AMapLoader.load({
      key: '558906b68a6d7d85c061d1ffce3abebf',
      version: '2.0',
      plugins: [
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.Geolocation',
        'AMap.PlaceSearch',
        'AMap.Geocoder',
        'AMap.HawkEye',
        'AMap.MapType',
        'AMap.CircleEditor',
        'AMap.MouseTool',
        'AMap.AutoComplete',
        'AMap.PlaceSearch',
        'AMap.Driving',
        'AMap.Weather' // 添加天气插件
      ],
    });

    AMapObj = AMap;
    map = new AMap.Map('amap', {
      zoom: 12,
      resizeEnable: true,
      center: [115.490696, 38.8579735],
      viewMode: "3D",
    });

    // 初始化控件
    const mapType = new AMap.MapType();
    const hawkEye = new AMap.HawkEye();
    const toolbar = new AMap.ToolBar({position: 'LT'});
    const scale = new AMap.Scale();
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0,
      convert: true,
      showButton: true,
      buttonPosition: 'LB',
      buttonOffset: new AMap.Pixel(10, 20),
      showMarker: true,
      showCircle: true,
      panToLocation: true,
      zoomToAccuracy: true,
    });

    geocoder = new AMap.Geocoder({city: '全国'});

    // 添加控件到地图
    map.addControl(geolocation);
    map.addControl(toolbar);
    map.addControl(scale);
    map.addControl(hawkEye);
    map.addControl(mapType);

    poiSeatch()
    bindEvent()
    getWeather('保定市'); // 初始化时获取默认天气
  } catch (error) {
    console.error('地图加载失败:', error);
  }
}

const poiSeatch=()=>{
  auto.value = new AMap.AutoComplete(autoOptions)
  const placeSearch = new AMap.PlaceSearch({
    map: map,
    city: '', // 减小搜索范围至某个城市
    pageSize: 5, // 单页显示结果条数
    pageIndex: 1, // 页码
    citylimit: false, // 是否强制限制在设置的城市内搜索
    autoFitView: true,
    panel: "panel", // 结果列表将在此容器中进行展示。出不来时设置样式z-inde: 999
  })
  auto.value.on("select", function (e) {
    //针对选中的poi实现自己的功能
    placeSearch.search(e.poi.name);
  });
}

// 鼠标双击事件
const doubleClick = (e) => {
  console.log('您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置双击了地图！')

}

// 鼠标移动事件
const showInfoMove = () => {
  console.log('您移动了您的鼠标！')
}

// 鼠标点击事件
const signClick = (e) => {
  console.log('您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置单击了地图！')
  const x = e.lnglat.getLng()
  const y = e.lnglat.getLat()
  showInfo(e,x,y)
  geocoder.getAddress(e.lnglat, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      const city = result.regeocode.addressComponent.city;
      if (city) {
        getWeather(city);
      }
    }
  });
}

// 地图事件绑定
const bindEvent = () => {
  console.log("事件绑定成功")
  map.on('click', signClick);
  // map.on('dblclick', doubleClick);
  // map.on('mousemove', showInfoMove);
}


// 路径规划
const goView = () => {
  // eslint-disable-next-line no-undef
  const driving = new AMapObj.Driving({
    map,
    // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
    // eslint-disable-next-line no-undef
    // policy: AMapObj.DrivingPolicy.LEAST_TIME  // 路线最快
    policy: rule.value  // 路线最快
  })
  const points = [
    { keyword: startName.value, city: startName.value },
    { keyword: endName.value, city: endName.value }
  ]

  driving.search(points, (status, result) => {
    // 未出错时，result即是对应的路线规划方案
    console.log('status=', status)
    console.log('result=', result)
    if (status === 'complete') {
      routeArr.value = result.routes[0].steps
      policy.value = result.routes[0].policy
      console.log(routeArr.value)
    }
  })
}

const showInfo = (e, x, y) => {
  geocoder.getAddress(e.lnglat, (status, result) => {
    // 修正拼写错误：'complier' -> 'complete'，regecode -> regeocode
    if (status === 'complete' && result.regeocode) {
      const address = result.regeocode.formattedAddress;
      const city = result.regeocode.addressComponent.city;
      if(city) {
        getWeather(city); // 点击地图时更新天气
      }
      const infoContent = `
        <div style="padding:7px 0px 0px 0px;">
          <div class="global-header">当前位置</div>
          <p class='input-item'>经度: ${x}</p>
          <p class='input-item'>纬度: ${y}</p>
          <p class='input-item'>地址: ${address}</p>
        </div>
      `;
      const infoWindow = new AMapObj.InfoWindow({
        content: infoContent
      });
      infoWindow.open(map, new AMapObj.LngLat(x, y));
    } else {
      console.error('获取地址失败');
    }
  });
};

// 获取天气
const getWeather = (city) => {
  if (!AMapObj) return;
  const weather = new AMapObj.Weather();
  weather.getLive(city, (err, data) => {
    if (!err) {
      weatherInfo.value = data;
      console.log('天气数据:', data);
    } else {
      console.error('获取天气失败:', err);
    }
  });
}

onUnmounted(() => {
  if (map) {
    map.destroy(); // 修正：卸载时销毁地图
    map = null;
  }
});
</script>

<style scoped lang="less">
.map-wrapper {
  position: relative; /* 添加相对定位，以便天气面板可以相对于它定位 */
  #amap {
    width: 2000px;
    height: 1000px;
  }
}
#panel{
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
}

.weather-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  width: 220px;
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  color: #303133;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
  overflow: hidden;
  transition: all 0.3s ease;
}

.weather-panel:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.weather-header {
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 600;
  background-color: rgba(64, 158, 255, 0.1);
  border-bottom: 1px solid rgba(64, 158, 255, 0.2);
}

.weather-body {
  padding: 16px;
  text-align: center;
}

.temperature {
  font-size: 42px;
  font-weight: bold;
  line-height: 1;
}

.weather-condition {
  font-size: 18px;
  margin-top: 8px;
  color: #606266;
}

.weather-footer {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  font-size: 13px;
  background-color: rgba(0, 0, 0, 0.02);
  border-top: 1px solid #f0f2f5;
  color: #909399;
}
</style>